package com.lanou3g.ptp.teachlink.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.entity.Student;
import com.lanou3g.ptp.entity.Teachlink;
import com.lanou3g.ptp.teachlink.mapper.TeachlinkMapper;
import com.lanou3g.ptp.teachlink.service.TeachlinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TeachlinkServiceImpl implements TeachlinkService {
    @Autowired
    private TeachlinkMapper teachlinkMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${REDIS_TEACHLINK_KEY_PREFIX}")
    private String REDIS_TEACHLINK_KEY_PREFIX;

    @Value("${REDIS_TEACHLINK_KEY_EXPIRE}")
    private Long REDIS_TEACHLINK_KEY_EXPIRE;

    @Override
    public PageInfo<Teachlink> findAll(Integer page, Integer size) {
        PageHelper.startPage(page,size);

        List<Teachlink> teachlinks = teachlinkMapper.findAll();

        return new PageInfo<>(teachlinks);
    }

    @Override
    public PageInfo<Teachlink> findByKeyword(Integer page, Integer size, String keyword){
        PageHelper.startPage(page,size);

        List<Teachlink> byKeyword = teachlinkMapper.findByKeyword("%" + keyword + "%");

        return new PageInfo<>(byKeyword);
    }

    @Override
    public Teachlink findById(Long id){
        String s = REDIS_TEACHLINK_KEY_PREFIX + id;
        String s1 = redisTemplate.opsForValue().get(s);
        if (s1==null){
            Teachlink teachlink = teachlinkMapper.findById(id);
            String s2 = JSON.toJSONString(teachlink);
            redisTemplate.opsForValue().set(s,s2,REDIS_TEACHLINK_KEY_EXPIRE, TimeUnit.SECONDS);
            return teachlink;
        }else {
            redisTemplate.expire(s,REDIS_TEACHLINK_KEY_EXPIRE,TimeUnit.SECONDS);
            return JSON.parseObject(s1, Teachlink.class);
        }

    }

    @Override
    public void insert(Teachlink teachlink) {
        teachlink.setCreateTime(new Date());
        teachlink.setUpdateTime(new Date());
        teachlinkMapper.insert(teachlink);
    }

    @Override
    public void update(Long id,Teachlink teachlink) {
        teachlink.setUpdateTime(new Date());
        teachlinkMapper.update(id,teachlink);
    }

    @Override
    public void delete(Long id) {
        teachlinkMapper.delete(id);
    }

    @Override
    public void deletes(Long[] ids) {
        teachlinkMapper.deletes(ids);
    }

}
